package com.heima.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.PageResult;
import com.heima.pojo.Partner;
import com.heima.pojo.dto.PartnerDto;
import com.heima.pojo.vo.PartnerVo;
import com.heima.service.IPartnerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 合作商表 前端控制器
 *
 * @author xjy
 * @since 2024-06-04
 */
@RestController
@RequestMapping("/user-service/partner")
@Api(tags = "合作商管理")
public class PartnerController {
    @Autowired
    private IPartnerService tbPartnerService;

    @PostMapping
    @ApiOperation("添加合作商")
    public Boolean addPartner(@RequestBody PartnerDto partnerDto) {
        if (ObjectUtil.isEmpty(partnerDto)) {
            return false;
        }
        partnerDto.setCreateTime(LocalDateTime.now());
        partnerDto.setUpdateTime(LocalDateTime.now());
        return tbPartnerService.save(BeanUtil.toBean(partnerDto, Partner.class));
    }

    @GetMapping("/search")
    @ApiOperation("分页查询合作商列表")
    public PageResult<PartnerVo> search(PageResult<PartnerVo> pageResult, @RequestParam(required = false) String name) {
        return tbPartnerService.search(pageResult, name);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询合作商")
    public PartnerVo getPartnerById(@PathVariable @ApiParam(value = "合作商id", required = true) Long id) {
        return tbPartnerService.getPartnerById(id);
    }

    @PutMapping("/{id}")
    @ApiOperation("修改合作商")
    public Boolean updatePartner(@PathVariable @ApiParam(value = "合作商id", required = true) Long id,
                                 @RequestBody PartnerDto partnerDto) {
        if (ObjectUtil.isEmpty(partnerDto) || ObjectUtil.isEmpty(id)) {
            return false;
        }
        partnerDto.setUpdateTime(LocalDateTime.now());
        LambdaUpdateWrapper<Partner> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Partner::getId, id);
        return tbPartnerService.update(BeanUtil.toBean(partnerDto, Partner.class), updateWrapper);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除合作商")
    public Boolean deletePartner(@PathVariable @ApiParam(value = "合作商id", required = true) Long id) {
        if (ObjectUtil.isEmpty(id)) {
            return false;
        }
        return tbPartnerService.removeById(id);
    }

    @GetMapping("/count")
    @ApiOperation("获取合作商数量")
    public Integer count() {
        return tbPartnerService.count();
    }
}
